package com.bbird.od.finance.service.models.excel;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.property.ExcelContentProperty;

import java.lang.reflect.Method;

/**
 * @author ziyang Kuang
 * @date 2020/11/17
 * @describe
 */
public class EnumToExcelConverter implements Converter<Object> {

    /**
     * 转换后数据类型
     */
    @Override
    public Class supportJavaTypeKey() {
        return Enum.class;
    }

    /**
     * 转换前Excel单元格实际值数据类型
     */
    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    /**
     * Excel解析成Java时调用
     */
    @Override
    public Object convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        String labelName = cellData.getStringValue();

        Class<?> clazz = contentProperty.getField().getType();
        Object[] enumConstants = clazz.getEnumConstants();
        for (Object enumConstant : enumConstants) {
            Object labelNameTemp = enumConstant.getClass().getMethod("getLabel").invoke(enumConstant);
            if (labelName.equals(labelNameTemp)) {
                return enumConstant;
            }
        }
        return null;
    }

    /**
     * Java生成Excel时调用，不用管
     */
    @Override
    public CellData convertToExcelData(Object value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        Method getLabel = value.getClass().getMethod("getLabel");
        Object label = getLabel.invoke(value);
        return new CellData(String.valueOf(label));
    }

}
